package org.wattdepot.cli;

import javax.xml.datatype.XMLGregorianCalendar;
import org.wattdepot.client.BadXmlException;
import org.wattdepot.client.MiscClientException;
import org.wattdepot.client.NotAuthorizedException;
import org.wattdepot.client.ResourceNotFoundException;
import org.wattdepot.client.WattDepotClient;
import org.wattdepot.util.tstamp.Tstamp;

/**
 * Responsible for all carbon content functionality.
 * 
 * @author Aaron Herres
 * 
 */

public class CarbonContent implements SingleCommand {
  /**
   * processes the total carbon content command, returns a message.
   * 
   * @param client The WattDepotClient to use in connections.
   * @param args The argument string.
   * @return the output message.
   */
  @Override
  public String processCommand(WattDepotClient client, String[] args) {
    String source;
    XMLGregorianCalendar time;
    int samplingInterval = 0;
    if (!client.isHealthy()) {
      return Messages.Error.CLIENT_NOT_READY;
    }
    if (args.length < 5) {
      return usageString();
    }
    source = args[1];
    try {
      samplingInterval = Integer.parseInt(args[4]);
    }
    catch (Exception e) {
      return Messages.Error.INVALID_INPUT;
    }
    try {

      time = Tstamp.makeTimestamp(args[2]);

    }
    catch (Exception e) {

      return Messages.Error.INVALID_TIMESTAMP;

    }

    double carbonGenerated;
    try {
      carbonGenerated =
          client.getCarbonEmitted(source, time, Tstamp.incrementHours(time, 1), samplingInterval)
              / client.getEnergyGenerated(source, time, Tstamp.incrementHours(time, 1),
                  samplingInterval);
    }
    catch (NotAuthorizedException e) {
      // TODO Auto-generated catch block
      return Messages.Error.NOT_AUTHORIZED;
    }
    catch (ResourceNotFoundException e) {
      // TODO Auto-generated catch block
      return Messages.Error.RESOURCE_NOT_FOUND;
    }
    catch (BadXmlException e) {
      // TODO Auto-generated catch block
      return Messages.Error.BAD_XML;
    }
    catch (MiscClientException e) {
      // TODO Auto-generated catch block
      return Messages.Error.CLIENT_NOT_READY;
    }

    return Double.toString(carbonGenerated * 1000) + " lbs CO2/MWh";

  }

  /*
   * returns a command-specific usage string.
   * 
   * @return usage for this class.
   * 
   * @see org.wattdepot.cli.SingleCommand#usageString()
   */
  @Override
  public String usageString() {
    return "Usage: carboncontent {source} {timestamp} sampling-interval {interval}";
  }

}
